"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig");
const SystemErrException = require("../../exception/systemError");
const LogicErrException = require("../../exception/logicError");
const { getOpenId } = require("../../utils/wxTools");
const await = require("await-stream-ready/lib/await");
const { post } = require("../../utils/YunGouOs/util/HttpUtil");

class UserService extends Service {

  async login(postData) {
    let transaction;
    try {
      const { userName, password, wxId, nickName, avatarUrl } = postData;
      const { ctx } = this;
      // 更新账号信息，和微信信息绑定
      let staff = await ctx.model.Organization.Staff.findAll({
        where: {
          userName,
          password
        },
        include: [{
          model: ctx.model.Organization.Role
        }, {
          model: ctx.model.Organization.Departments,
          include: {
            model: ctx.model.Organization.Units
          }
        }],
      });
      staff = JSON.parse(JSON.stringify(staff))[0];
      if (!staff) {
        return {
          data: '',
          code: -1,
          message: "账号或密码错误",
        };
      }
      if (staff.ORoles.length == 0) {
        return {
          data: '',
          code: -1,
          message: "账号未配置角色，请联系管理员",
        };
      }
      let roles = staff.ORoles.map(role => role.name);

      let { id: staffId, userName: staffName, ODepartment } = staff;
      await ctx.model.Organization.Staff.update(
        { wxId, wxName: nickName, wxAvatar: avatarUrl },
        {
          where: { id: staffId },
        }
      );
      let result = { nickName, avatarUrl, staffId, staffName, roles, departmentId: ODepartment.id, unitId: ODepartment.OUnit.id };
      return {
        data: result,
        code: httpCode.SUCCESS,
        message: "登录成功！",
      };
    } catch (error) {
      this.ctx.logger.error(error);
      await transaction.rollback();
    }
  }

  async monitorPartners(postData) {
    try {
      const { ctx } = this;
      let rows = await ctx.model.Videos.MonitorPartners.findAll({
        raw: true,
        order: [['create_date', 'desc']]
      });
      let statusOpts = ['设防中', '滞留车辆数预警', '滞留时间预警', '警报中', '排查中', '停止工作'];
      rows.forEach(row => {
        row.statusName = statusOpts[row.status - 1]
      });
      return {
        data: rows,
        code: httpCode.SUCCESS,
        message: "设备组查询成功",
      };
    } catch (error) {
      this.ctx.logger.error(error);
    }
  }
}

module.exports = UserService;
